package com.ofps.forms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ofps.common.utils.StringUtils;
import com.ofps.forms.common.utils.R;
import com.ofps.forms.domain.Dto.RecordDto;
import com.ofps.forms.domain.MyForm;
import com.ofps.forms.domain.WriteRecord;
import com.ofps.forms.mapper.WriteRecordMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import static com.ofps.common.utils.SecurityUtils.getUserId;

/**
 * .
 *
 * @author pyn 2022/6/13
 */
@Service("writeRecordService")

public class WriteRecordServiceImpl extends ServiceImpl<WriteRecordMapper, WriteRecord> {
    @Resource
    private WriteRecordMapper recordMapper;

    public R myList(RecordDto recordDto) {
        QueryWrapper<WriteRecord> queryWrapper = new QueryWrapper<>();
        Long userId = getUserId();
        queryWrapper

                //流程名称
                .like(StringUtils.isNotNull(recordDto.getFormName()), "form_name", recordDto.getFormName())
                .eq("user_id", userId)
                .eq(StringUtils.isNotNull(recordDto.getIsSubmit()), "is_submit", recordDto.getIsSubmit())
                //标签
                .like(StringUtils.isNotNull(recordDto.getFormTags()) && !recordDto.getFormTags().equals(","), "form_tags", recordDto.getFormTags())
                //创建时间
                .apply(recordDto.getDateRange() != null && StringUtils.isNotNull(recordDto.getDateRange().get("beginTime")),
                        "date_format (time,'%Y-%m-%d') >= date_format('" + recordDto.getDateRange().get("beginTime") + "','%Y-%m-%d')")
                .apply(recordDto.getDateRange() != null && StringUtils.isNotNull(recordDto.getDateRange().get("endTime")),
                        "date_format (time,'%Y-%m-%d') <= date_format('" + recordDto.getDateRange().get("endTime") + "','%Y-%m-%d')");

        Page<WriteRecord> recordList = recordMapper.selectPage(
                new Page<>(recordDto.getPageNo(), recordDto.getPageSize()), queryWrapper);
        Long counts = recordMapper.selectCount(queryWrapper);

        return null == recordList ? R.ok("暂无表单!") : R.ok("查询成功").put("counts", counts).put("records", recordList.getRecords());
    }
}
